package com.jy.appmarket.activity;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

import com.jy.appmarket.R;
import com.jy.appmarket.adapter.GalleryAdapter;
import com.jy.appmarket.adapter.GalleryPopupWindowAdapter;
import com.jy.appmarket.model.ImageFloderInfo;
import com.jy.appmarket.utils.GalleryImageLoader;
import com.jy.appmarket.utils.StorageConfig;
import com.umeng.analytics.MobclickAgent;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class GalleryActivity extends Activity implements OnItemClickListener, OnClickListener {
	private static final int PHOTO_REQUEST_CAREMA = 0;
	private static final int PHOTO_REQUEST_CUT = 1;

	// 存储文件夹中的图片数量
	private int mImgCount;
	// 要显示的图片文件夹
	private File mImgDir;
	private GridView mGirdView;
	private GalleryAdapter mAdapter;

	// 图片文件名
	private List<String> mImgs = new ArrayList<String>();
	private List<ImageFloderInfo> mImageFloders = new ArrayList<ImageFloderInfo>();
	private FileComparator mFileComparator = new FileComparator();

	private PopupWindow mPopupWindow;
	private RelativeLayout mBottomLayout;
	private TextView mCurrentDirText;
	private ImageView mBottomDivider;
	private int mScreenHeight;
	private Uri mTempFileUri = Uri.parse("file://" + StorageConfig.ROOT_DIR + "/head_icon_temp_file.jpg");

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			loadData();
			initPopupWindow();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gallery);

		initTitle();
		initViews();
		getImages();
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("选择图片");
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	private void initViews() {
		mGirdView = findViewById(R.id.picture_gridview);
		mGirdView.setOnItemClickListener(this);
		mBottomLayout = findViewById(R.id.bootom_layout);
		mBottomLayout.setOnClickListener(this);
		mCurrentDirText = findViewById(R.id.current_dir_text);
		mBottomDivider = findViewById(R.id.bootom_divider);

		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		mScreenHeight = outMetrics.heightPixels;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bootom_layout:
			showPopupWindow();
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position == 0) {
			camera();
		} else {
			File file = new File(mImgDir.getAbsolutePath() + "/" + mImgs.get(position));
			Uri uri = Uri.fromFile(file);
			crop(uri, mTempFileUri);
		}
	}

	public void camera() {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mTempFileUri);
		startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
	}

	private void crop(Uri inputUri, Uri outputUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(inputUri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 100);
		intent.putExtra("outputY", 100);

		intent.putExtra("scale", true);// 去黑边
		intent.putExtra("scaleUpIfNeeded", true);// 去黑边
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());// 图片格式
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
		intent.putExtra("return-data", false);
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	private void loadData() {
		if (mImgDir == null) {
			Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
			mImgs.clear();
			mImgs.add(0, "camera");
			mAdapter = new GalleryAdapter(this, "");
			mAdapter.setList(mImgs);
			mGirdView.setAdapter(mAdapter);
			return;
		}
		File[] imgs = mImgDir.listFiles();
		if (imgs == null) {
			return;
		}
		Arrays.sort(imgs, mFileComparator);
		mImgs.clear();
		mImgs.add(0, "camera");
		for (int i = 0; i < imgs.length; i++) {
			if (isImageFile(imgs[i])) {
				mImgs.add(imgs[i].getName());
			}
		}

		// 文件夹的路径和图片的路径分开保存，减少了内存的消耗；
		mAdapter = new GalleryAdapter(this, mImgDir.getAbsolutePath());
		mAdapter.setList(mImgs);
		mGirdView.setAdapter(mAdapter);
		mCurrentDirText.setText(mImgDir.getName());
	}

    private void initPopupWindow() {
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = layoutInflater.inflate(R.layout.gallery_popup_window_layout, null);
		ListView listView = view.findViewById(R.id.image_floder_listview);
		GalleryPopupWindowAdapter groupAdapter = new GalleryPopupWindowAdapter(this);
		groupAdapter.setList(mImageFloders);
		listView.setAdapter(groupAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ImageFloderInfo info = mImageFloders.get(position);
				if (!info.getDir().equals(mImgDir.getAbsolutePath())) {
					mImgDir = new File(info.getDir());
					loadData();
				}
				mPopupWindow.dismiss();
			}
		});
		mPopupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7));
		mPopupWindow.setAnimationStyle(R.style.AnimPopupBottom);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setFocusable(true);
	}

	private void showPopupWindow() {
		if (mImageFloders.size() == 0) {
			return;
		}
		// // 设置背景颜色变暗
		// WindowManager.LayoutParams lp = getWindow().getAttributes();
		// lp.alpha = 0.3f;
		// getWindow().setAttributes(lp);
		mPopupWindow.showAsDropDown(mBottomDivider, 0, 0);
	}

	private boolean isImageFile(File file) {
		if (file == null) {
			return false;
		}
		if (!file.isFile()) {
			return false;
		}
		String filename = file.getName();
        return filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jpeg");
    }

	/**
	 * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描，最终获得jpg最多的那个文件夹
	 */
	private void getImages() {
		if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
			return;
		}

		new Thread(new Runnable() {
			@Override
			public void run() {
				// 临时的辅助类，用于防止同一个文件夹的多次扫描
				HashSet<String> dirPaths = new HashSet<String>();
				String firstImage = null;
				Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = getContentResolver();

				// 只查询jpeg和png的图片
				Cursor cursor = mContentResolver.query(imageUri, null,
						MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
						new String[] { "image/jpeg", "image/png" }, MediaStore.Images.Media.DATE_MODIFIED + " DESC");

				while (cursor.moveToNext()) {
					// 获取图片的路径
					String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
					File file = new File(path);
					if (!file.exists()) {
						continue;
					}
					if (!file.canRead()) {
						continue;
					}
					// 拿到第一张图片的路径
					if (firstImage == null)
						firstImage = path;
					// 获取该图片的父路径名
					File parentFile = new File(path).getParentFile();
					if (parentFile == null) {
						continue;
					}
					String dirPath = parentFile.getAbsolutePath();
					ImageFloderInfo imageFloder = null;
					if (dirPaths.contains(dirPath)) {
						continue;
					} else {
						dirPaths.add(dirPath);
						imageFloder = new ImageFloderInfo();
						imageFloder.setDir(dirPath);
						imageFloder.setFirstImagePath(path);
					}

					int imgCount = parentFile.list(new FilenameFilter() {
						@Override
						public boolean accept(File dir, String filename) {
                            return filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jpeg");
                        }
					}).length;
					imageFloder.setCount(imgCount);
					mImageFloders.add(imageFloder);
					if (imgCount > mImgCount) {
						mImgCount = imgCount;
						mImgDir = parentFile;
					}
				}
				cursor.close();
				mHandler.sendEmptyMessage(0x001);
			}
		}).start();
	}

	private class FileComparator implements Comparator<File> {

		@Override
		public int compare(File lhs, File rhs) {
			if (lhs.lastModified() > rhs.lastModified()) {
				return -1;
			} else if (lhs.lastModified() == rhs.lastModified()) {
				return 0;
			} else {
				return 1;
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_CAREMA && resultCode == RESULT_OK) {
			// 从相机返回的数据
			if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
				crop(mTempFileUri, mTempFileUri);
			} else {
				Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
			}

		} else if (requestCode == PHOTO_REQUEST_CUT && resultCode == RESULT_OK) {
			File file = new File(mTempFileUri.getPath());
			if (file.exists()) {
				Intent resultData = new Intent();
				resultData.putExtra("head_icon_path", file.getAbsolutePath());
				setResult(RESULT_OK, resultData);
				finish();
			} else {
				Toast.makeText(this, "保存图片失败！", Toast.LENGTH_SHORT).show();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onDestroy() {
		GalleryImageLoader.getInstance().clearCache();
		super.onDestroy();
	}
}
